package com.le.tester.book.concurrentchallenge.synchronous;

import com.le.tester.entity.Product;
import com.le.tester.javaThink.fifth.chapter18_Str.DatabaseException;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * createTime：2025-03-26 10:11
 * description：预先加载稍后需要的数据
 */
public class PreLoader {
    private final FutureTask<Product> futureTask = new FutureTask<Product>(() -> loadProductInfo()) {

    };

    private Product loadProductInfo() {
        return new Product();
    }

    private final Thread thread = new Thread(futureTask);

    public void start() {
        thread.start();
    }

    public Product get() throws Throwable {
        try {
            return futureTask.get();
        } catch (InterruptedException | ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof DatabaseException) {
                throw cause;
            } else {
                throw new RuntimeException();
            }
        }
    }
}
